//
//  NEBaseTeamHistoryUserMessageResultController.swift
//  NETeamUIKit
//
//  Created by Laura on 2024/7/31.
//

import NECommonKit
import NIMSDK
import UIKit

@objcMembers
open class NEBaseTeamHistoryUserMessageResultController: NEBaseViewController, UITableViewDelegate, UITableViewDataSource {
    public let viewModel = TeamHistoryMessageViewModel()
    
    /// 群id
    public var teamId: String?
    public var user: NECoreIM2Kit.NEUserWithFriend?
    
    var tag = "TeamHistoryUserMessageResultController"
    
    /// 历史消息列表
    public lazy var tableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .plain)
        tableView.translatesAutoresizingMaskIntoConstraints = false
        tableView.separatorStyle = .none
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(
            NEBaseTeamSearchUserCell.self,
            forCellReuseIdentifier: "\(NSStringFromClass(NEBaseTeamSearchUserCell.self))"
        )
        tableView.rowHeight = 65
        tableView.backgroundColor = .white
        tableView.sectionHeaderHeight = 30
        tableView.sectionFooterHeight = 0
        tableView.keyboardDismissMode = .onDrag
        
        if #available(iOS 11.0, *) {
            tableView.estimatedRowHeight = 0
            tableView.estimatedSectionHeaderHeight = 0
            tableView.estimatedSectionFooterHeight = 0
        }
        if #available(iOS 15.0, *) {
            tableView.sectionHeaderTopPadding = 0.0
        }
        return tableView
    }()
    
    /// 空占位图
    public lazy var emptyView: NEEmptyDataView = {
        let view = NEEmptyDataView(
            imageName: "emptyView",
            content: localizable("no_search_results"),
            frame: CGRect.zero
        )
        view.translatesAutoresizingMaskIntoConstraints = false
        view.isUserInteractionEnabled = false
        view.isHidden = true
        return view
        
    }()
    
    public init(teamId: String?, user: NECoreIM2Kit.NEUserWithFriend?) {
        super.init(nibName: nil, bundle: nil)
        self.teamId = teamId
        self.user = user
    }
    
    public required init?(coder: NSCoder) {
        super.init(coder: coder)
    }
    
    override open func viewDidLoad() {
        super.viewDidLoad()
        weak var weakSelf = self
        
        navigationView.moreButton.isHidden = true
        
        viewModel.getTeamInfo(teamId) { team, error in
            if team?.isValidTeam == false || team == nil {
                weakSelf?.view.makeToast(localizable("team_not_exist"))
            }
        }
        setupSubviews()
        initialConfig()
        
        toSearchHistory()
    }
    
    open func setupSubviews() {
        view.addSubview(tableView)
        view.addSubview(emptyView)
        
        emptyView.isHidden = true
        
        NSLayoutConstraint.activate([
            emptyView.rightAnchor.constraint(equalTo: tableView.rightAnchor),
            emptyView.leftAnchor.constraint(equalTo: tableView.leftAnchor),
            emptyView.bottomAnchor.constraint(equalTo: tableView.bottomAnchor),
            emptyView.topAnchor.constraint(equalTo: tableView.topAnchor),
        ])
    }
    
    open func initialConfig() {
        title = localizable("historical_record_member")
    }
    
    /// 搜索历史消息
    func toSearchHistory() {
        viewModel.searchResultInfos?.removeAll()
        emptyView.isHidden = true
        tableView.reloadData()
        
        guard let teamId = teamId else {
            return
        }
        weak var weakSelf = self
        weakSelf?.viewModel.searchHistoryUserMessages(teamId, userId: user?.user?.accountId ?? "") { error, messages in
            NEALog.infoLog(
                ModuleName + " " + self.tag,
                desc: "CALLBACK searchHistoryUserMessages " + (error?.localizedDescription ?? "no error")
            )
            if error == nil {
                if let msg = messages, msg.count > 0 {
                    weakSelf?.emptyView.isHidden = true
                } else {
                    weakSelf?.emptyView.isHidden = false
                }
                weakSelf?.tableView.reloadData()
            } else {
                NEALog.errorLog(
                    ModuleName + " " + (weakSelf?.tag ?? "TeamHistoryMessageController"),
                    desc: "searchMessages failed, error = \(error!)"
                )
            }
        }
    }
    
    // MARK: UITableViewDelegate, UITableViewDataSource
    
    open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        viewModel.searchUserResultInfos.count
    }
    
    open func tableView(_ tableView: UITableView,
                        cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        UITableViewCell()
    }
    
    public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 64
    }
    
    open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let cellModel = viewModel.searchUserResultInfos[indexPath.row]
        if cellModel.conversationType == .CONVERSATION_TYPE_TEAM {
            if let conversationId = cellModel.conversationId {
                Router.shared.use(
                    PushTeamChatVCRouter,
                    parameters: ["nav": navigationController as Any,
                                 "conversationId": conversationId as Any,
                                 "anchor": cellModel],
                    closure: nil
                )
            }
        }
    }
}
